<template>
  <div id="exportIndex" v-loading="loading">
    <div class="button-box">
      <el-button @click="showExportRecordDialog()" type="primary">导出记录</el-button>
    </div>
    <div class="contentBox">
      <div v-if="selectData.length !== 0" class="detail">
        <div class="content-header">
          <div class="add-btn" @click="showExportListDialog">
            <i class="el-icon-plus"></i>
          </div>
          <span>继续添加需要导出的事项</span>
        </div>
        <div class="content-body">
          <el-table :data="selectData" border style="width: 100%" height="440">
            <el-table-column prop="itemCodeProd" label="事项编码"></el-table-column>
            <el-table-column prop="itemName" label="事项名称"></el-table-column>
            <el-table-column prop="areaName" label="所属地区"></el-table-column>
            <el-table-column prop="itemDeptName" label="所属部门"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="handleRemove(scope.$index)" type="text" size="small">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="selected-num">
          <span>已选择{{selectData.length}}个事项</span>
        </div>
      </div>
      <div v-else class="select" @click="showExportListDialog">
        <img src="@/assets/img/export.png" />
        <p>请选择需要导出的事项</p>
      </div>
    </div>
    <div class="footerBox">
      <div style="margin-bottom:30px">
        <span>选择导出内容类型：</span>
        <el-select placeholder="请选择" v-model="exportType">
          <el-option
            v-for="item in exportTypeDict"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <el-button @click="handleExport()" type="primary">确认导出</el-button>
    </div>
    <!-- 导出列表 -->
    <el-dialog
      class="ExportList sideDialog"
      title="选择导出的事项"
      :visible.sync="ExportListDialog"
      :before-close="handleClose"
    >
      <el-container>
        <el-main>
          <el-row :gutter="10">
            <el-col :span="5">
              <vTreeSelectionArea
                @appEvent="getAreaNode"
                @clearEvent="clearArea"
                ref="areaChild"
                :treeData="areaData"
                :width="`${200}px`"
                class="handle-input"
              ></vTreeSelectionArea>
            </el-col>
            <el-col :span="5">
              <vTreeSelectionOrg
                @appEvent="getOrgNode"
                @clearEvent="clearOrg"
                ref="orgChild"
                :treeData="orgData"
                :width="`${200}px`"
                class="handle-input"
              ></vTreeSelectionOrg>
            </el-col>
            <el-col :span="5">
              <el-input v-model="itemCodeProd" placeholder="请输入事项编码"></el-input>
            </el-col>
            <el-col :span="5">
              <el-input v-model="itemName" placeholder="请输入事项名称"></el-input>
            </el-col>
            <el-col :span="4">
              <el-button @click="pageChange(1)" type="primary">搜 索</el-button>
              <el-button @click="reset()">重 置</el-button>
            </el-col>
          </el-row>
          <el-table
            ref="exportTable"
            :data="exportData"
            style="width: 100%"
            row-key="id"
            @selection-change="selectionChange"
            lazy
            :load="loadChild"
            :tree-props="{
              children: 'children', 
              hasChildren: 'hasChildren'
            }"
          >
            <el-table-column type="selection" width="60"></el-table-column>
            <el-table-column prop="itemCodeProd" label="事项编码" width="200"></el-table-column>
            <el-table-column label="事项名称">
              <template slot-scope="scope">
                <div
                  :style="`padding-left:${(scope.row.parentItemCodes.split(',').length-1)*15}px`"
                >
                  <span v-if="scope.row.childNumber === 0">
                    <i class="sx-icon-Chencheguiding"></i>
                    {{scope.row.itemName}}
                  </span>
                  <span v-else>
                    <i class="sx-icon-wenjian"></i>
                    {{scope.row.itemName}}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="areaName" label="所属地区"></el-table-column>
            <el-table-column prop="itemDeptName" label="所属部门"></el-table-column>
          </el-table>
        </el-main>
        <div class="paginationBox">
          <el-pagination
            background
            layout="total, prev, pager, next, sizes"
            @current-change="pageChange"
            @size-change="sizeChange"
            :current-page="current"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="size"
            :total="total"
          ></el-pagination>
        </div>
        <el-footer class="footer-button">
          <el-button type="primary" @click="handleSelected">确认选择</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </el-footer>
      </el-container>
    </el-dialog>
    <!-- 导出记录 -->
    <EcportRecord ref="EcportRecord"></EcportRecord>
    <!-- 导出文件地址 -->
    <iframe class="hide" :src="exporturl" frameborder="0"></iframe>
  </div>
</template>

<script>
import * as commonApi from '@/api/commonApi.js'
import vTreeSelectionArea from '@/components/common/TreeSelectionArea'
import vTreeSelectionOrg from '@/components/common/TreeSelectionOrg'
import EcportRecord from '@/components/page/clopedia/dataApply/exportCenter/EcportRecord'
export default {
  name:'exportIndex',
  components:{
    EcportRecord,
    vTreeSelectionArea,
    vTreeSelectionOrg
  },
  data(){
    return{
      ExportListDialog:false,
      loading:false,
      current:1,
      size:10,
      total:10,
      exporturl:'',
      itemName:'',
      itemCodeProd:'',
      selectData:[],// 已选中的要导出的数据
      exportData:[],// 所有导出的数据
      exportType:'',
      exportTypeDict:[],
      selects:[],
      // 筛选条件
      areaId:'',
      organizeId:'',
      areaData: [],
      orgData:[],
      currentRegionId:'',
    }
  },
  mounted(){
    this.getDict('export_type','exportTypeDict')
    this.initData()
    this.getOrgList()
    this.getRegionList()
  },
  methods:{
    async getDict(type,arrName){
      let res = await this.$get(this.$Api.sysDict+type)
      this[arrName] = res.data.data
    },
    // 获取需要导出的事项
    initData(){
      let params = {
        areaId:this.areaId,
        itemDeptId:this.organizeId,
        itemCodeProd:this.itemCodeProd,
        itemName:this.itemName,
        current:this.current,
        size:this.size
      }
      this.loading = true
      this.$get(this.$Api.directoryList, params)
        .then(res => {
          if(res.data.statusCode === 200){
            this.exportData = res.data.data.directoryQueryDataPage.records
            this.exportData.forEach(item =>{
              item.childNumber > 0 ? this.$set(item, 'hasChildren', true) : this.$set(item, 'hasChildren', false)
              this.selectData.forEach(x => {
                if(item.id === x.id){
                  this.$refs.exportTable.toggleRowSelection(x)
                }
              })
            })
            this.current = res.data.data.directoryQueryDataPage.current
            this.size = res.data.data.directoryQueryDataPage.size
            this.total = res.data.data.directoryQueryDataPage.total
          }
          this.loading = false
        })
        .catch(err => {
          console.log(err);
          this.loading = false
        });
    },
    loadChild(row, treeNode, resolve){
      // console.log(row)
      this.$get(this.$Api.directoryChildList, {
        parentItemCode:row.itemCode
      })
        .then(res => {
          if(res.data.statusCode === 200){
            let childData = res.data.data
            childData.forEach(item =>{
              item.childNumber > 0 ? this.$set(item, 'hasChildren', true) : this.$set(item, 'hasChildren', false)
            })
            resolve(childData)
          }
        })
    },
    selectionChange(data){
      // console.log(data)
      this.selects = data
      // this.selectData = data
    },
    // 确认选择
    handleSelected(){
      console.log(this.selects)
      this.selects.forEach(item => {
        this.selectData.push(item)
      })
      this.selectData = this.delRepeat(this.selectData)
      // this.ExportListDialog = false
    },
    // 去重
    delRepeat(arr){
      let hash = {};
      arr = arr.reduce((preVal, curVal) => {
        hash[curVal.id] ? '' : hash[curVal.id] = true && preVal.push(curVal); 
        return preVal 
      }, [])
      return arr
    },
    // 确认导出
    handleExport(){
      if(this.exportType === ''){
        this.$message({
          message: '请选择导出内容类型',
          type: 'warning'
        })
        return false
      }
      if(this.selectData.length > 11){
        this.$message({ message: '最多只能导出10条数据', type: 'warning' });
        return false
      }
      let params = {
        exportType:this.exportType,
        itemMap: {}
      }
      this.selectData.forEach(item => {
        this.$set(params.itemMap, item.itemCode, item.itemName)
      })
      // console.log(params)
      this.$axios({
        method: 'POST',
        url:this.$Api.export,
        data:params,
        responseType:'arraybuffer'
      })
      .then(res => {
          console.log(res)
          const blob = new Blob([res.data]);// ArrayBuffer
          const fileName = `${new Date().valueOf()}.zip`;
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          link.click();
          window.URL.revokeObjectURL(link.href);
      })
      // this.exporturl = ''
      // setTimeout(() => {
      //   this.exporturl = this.$Api.export+'?exportType='+this.exportType+'&itemCodes='+this.getItemCode(this.selectData)
      // })
    },
    showExportListDialog(){
      this.ExportListDialog = true
    },
    showExportRecordDialog(){
      this.$refs.EcportRecord.showListDialog()
    },
    // 移除
    handleRemove(index){
      this.exportData.forEach(item => { 
        if(this.selectData[index].id === item.id){
          this.$refs.exportTable.toggleRowSelection(item,false)// 回显
        }
      })
      this.selectData.splice(index,1)
    },
    handleClose(){
      this.ExportListDialog = false
    },
    getItemCode(arr){
      let codes = []
      arr.forEach(item => {
        codes.push(item.itemCode)
      })
      return codes.join()
    },
    pageChange(val){
      this.current = val
      // this.selects.forEach(item=>{// 翻页前将数据都保存
      //   this.selectData.push(item)
      // })
      // this.selectData = this.delRepeat(this.selectData)
      this.initData()
    },
    sizeChange(val){
      this.size = val
      this.initData()
    },
    reset(){
      this.itemName = ''
      this.itemCodeProd = ''
    },
    // 清除地区筛选条件
    clearArea(){
      this.areaId = '';
      this.currentRegionId = '';
      this.orgData=[];
      this.$refs.orgChild.childReset(); // 清除地区，同时清除机构筛选条件
    },
    // 清除机构筛选条件
    clearOrg(){
      this.organizeId = '';
    },
    // 子组件返回选中参数(区域id)
    getAreaNode(params){
      this.areaId = params.id;
      this.currentRegionId = params.id;
      this.getOrgList();
    },
    // 返回机构id
    getOrgNode(params){
      this.organizeId = params.id;
    },
    // 获取地区下拉列表
    getRegionList(){
      this.areaData = [];
      commonApi.getLoginAreaTreeList().then( res=> {
        if(res.data.statusCode == '200'){
          this.areaData = res.data.data;
        } else {
          if(res.data.msg.length > 20){
            this.$message.error('服务器接口异常，请联系管理员');
          } else {
            this.$message.error(res.data.msg);
          }
        }
      })
    },
    // 通过地区id获取部门列表
    getOrgList(){
      const regionId = this.currentRegionId;
      // if(!regionId){
      //   this.$message({
      //     message:'请先选择地区',
      //     type:'info'
      //   });
      //   this.orgData = [];
      //   return;
      // }
      commonApi.getLoginOrgTreeList({areaId: regionId}).then( res => {
        if(res.data.statusCode == '200'){
          this.orgData = res.data.data;
        } else {
          if(res.data.msg.length > 20){
            this.$message.error('服务器接口异常，请联系管理员');
          } else {
            this.$message.error(res.data.msg);
          }
        }
      }).catch(() => {
        this.$message.error('接口异常');
      })
    },
  }
}
</script>

<style lang="scss">
#exportIndex {
  position: relative;
  padding: 20px 30px;
  .button-box {
    position: absolute;
    top: -45px;
    right: 0;
  }
  .contentBox {
    width: 100%;
    min-height: 55vh;
    border: 1px #e7e7e7 solid;
    margin-bottom: 30px;
    position: relative;
    .content-header {
      height: 120px;
      line-height: 120px;
      text-align: center;
      .add-btn {
        display: inline-block;
        height: 60px;
        line-height: 60px;
        width: 60px;
        font-size: 36px;
        color: #1492ff;
        border: #1492ff 1px dashed;
        cursor: pointer;
        font-weight: 200;
        vertical-align: middle;
        margin-right: 10px;
      }
      span {
        font-size: 16px;
      }
    }
    .content-body {
      padding: 10px 20px 20px;
      .el-table td,
      .el-table th {
        padding: 0;
      }
    }
    .selected-num {
      width: 120px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      background-color: #fff;
      position: absolute;
      bottom: -12px;
      left: 50%;
      margin-left: -60px;
      letter-spacing: 1px;
    }
    .select {
      text-align: center;
      width: 160px;
      height: 180px;
      cursor: pointer;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -90px;
      margin-left: -80px;
      img {
        width: 80%;
        display: inline-block;
        margin-bottom: 20px;
      }
    }
  }
  .footerBox {
    text-align: center;
    .el-select {
      width: 360px;
      height: 36px;
    }
  }
  .ExportList {
    .el-main {
      height: 74vh;
      .el-table {
        .sx-icon-wenjian {
          color: #f7b500;
        }
        .el-table__row {
          background-color: #fff !important;
          .el-table__indent {
            padding-left: 0 !important;
          }
          .el-table__expand-icon {
            position: absolute;
            right: -10px;
            top: 11px;
            z-index: 999;
          }
          &.el-table__row--level-1 .el-table__expand-icon {
            right: -25px;
          }
          &.el-table__row--level-2 .el-table__expand-icon {
            right: -40px;
          }
          &.el-table__row--level-3 .el-table__expand-icon {
            right: -55px;
          }
        }
      }
    }
    .el-dialog {
      width: 1140px;
      .el-row {
        margin-bottom: 20px;
        .el-col-4 {
          overflow: hidden;
          text-align: left;
        }
      }
    }
    .logButton {
      width: 100%;
      height: 80px;
      border-top: 1px solid #c9c9c9;
      text-align: center;
      padding-top: 20px;
      margin-top: 20px;
    }
  }
}
</style>